package it.polimi.protopeer.simulation;

import java.net.InetAddress;
import java.net.UnknownHostException;

import protopeer.Experiment;
import protopeer.Finger;
import protopeer.NeighborManager;
import protopeer.Peer;
import protopeer.PeerFactory;
import protopeer.network.mina.MinaAddress;
import protopeer.servers.bootstrap.BootstrapClient;
import protopeer.servers.bootstrap.BootstrapServer;
import protopeer.servers.bootstrap.SimpleConnector;
import protopeer.servers.bootstrap.SimplePeerIdentifierGenerator;

public class PeerFactorySimulation implements PeerFactory {
	private NeighborManager neighborManager;
	private BootstrapServer bootstrapServer;
	private SimpleConnector simpleConnector;
	private SimplePeerIdentifierGenerator simplePeerGenerator;
	private String[] neighbors;
	
	public PeerFactorySimulation(String[] neighbors){
		super();
		neighborManager=new NeighborManager();
		bootstrapServer= new BootstrapServer();
		simpleConnector=new SimpleConnector();
		simplePeerGenerator=new SimplePeerIdentifierGenerator();
		this.neighbors=neighbors;
	}
	
	@Override
	public Peer createPeer(int peerIndex, Experiment experiment) {
		Peer newPeer = new Peer(peerIndex);
		if (peerIndex == 0) {
			newPeer.addPeerlet(bootstrapServer);
		}
		MinaAddress mAddress=null;
		for(int i=0;i<neighbors.length;i++){
			try {
				mAddress = new MinaAddress(InetAddress.getByName(neighbors[i]), 7000);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
			AddressPeerIdentifierGenerator addressGenerator= new AddressPeerIdentifierGenerator();
			Finger neigh=new Finger(mAddress,addressGenerator.generatePeerIdentifier(mAddress));
			neighborManager.addNeighbor(neigh);
		}
		newPeer.addPeerlet(neighborManager);
		newPeer.addPeerlet(simpleConnector);
		newPeer.addPeerlet(new BootstrapClient(Experiment
				.getSingleton().getAddressToBindTo(0),
				simplePeerGenerator));
		newPeer.addPeerlet(new CommandFlooder(peerIndex == 0));
		return newPeer;
	}

}
